package dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
        private static String driver;
        private static String url;
        private static String user;
        private static String pwd;
        Connection con=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        //读取配置信息
    static{
        init();
        }
        public static void init(){
            String p="datebase.properties";
            InputStream is = BaseDao.class.getClassLoader().getResourceAsStream(p);
            Properties properties = new Properties();
            try {
                properties.load(is);
                driver = properties.getProperty("driver");
                url = properties.getProperty("url");
                user = properties.getProperty("user");
                pwd = properties.getProperty("pwd");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //连接对象
    public Connection getConnection(){

       //加载驱动
        try {
            Class.forName(driver);
        //获取连接对象
            con= DriverManager.getConnection(url,user,pwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return con;
    }
         //查询方法
    public ResultSet executeQuery(String sql,Object...params){
        con=getConnection();
        try {
            pstmt=con.prepareStatement(sql);
            for (int i=0;i<params.length;i++){
                pstmt.setObject(i+1,params[i]);

            }
        rs=pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }
        //增/删/改通用方法
    public int executeUpdate(String sql,Object...params){
        con=getConnection();
        int count=0;
        try {
            pstmt=con.prepareStatement(sql);
            for (int i=0;i<params.length;i++){
                pstmt.setObject(i+1,params[i]);
            }
            count=pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }
        //释放资源
    public void closeAll(Connection con,PreparedStatement pstmt,ResultSet rs){
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstmt!=null){
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con!=null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
